package handler

import (
	"gitee.com/eqyun/gosdk/sdk/pkg"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type LoginUser struct {
	IdAuto   int    `gorm:"primaryKey;autoIncrement"`
	Name     string `gorm:"size:25;unique;comment:全员账号"`
	Password string `gorm:"size:255;not null;unique;comment:密码"`
	Type     string `gorm:"size:255;not null;comment:会员类型"`
	LinkId   int    `gorm:"index;comment:关联的账号id"`
	Superior int    `gorm:"comment:上级账号"`
}

func (e *LoginUser) Encrypt() (err error) {
	if e.Password == "" {
		return
	}
	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
		return
	} else {
		e.Password = string(hash)
		return
	}
}

func (LoginUser) TableName() string {
	return "login_user"
}

type Login struct {
	Username string `form:"UserName" json:"username" binding:"required"`
	Password string `form:"Password" json:"password" binding:"required"`
	Code     string `form:"Code" json:"code" binding:"required"`
	UUID     string `form:"UUID" json:"uuid" binding:"required"`
}

func (u *Login) GetUser(tx *gorm.DB) (user LoginUser, err error) {
	err = tx.Where("name=?", u.Username).First(&user).Error
	if err != nil {
		return
	}
	_, err = pkg.CompareHashAndPassword(user.Password, u.Password)

	if err != nil {
		return
	}
	return
}
